package com.interview.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 交替输出奇偶数的线程池示例
 * 
 * 功能说明：
 * - 使用 ExecutorService 线程池创建两个线程
 * - 线程1 输出所有奇数（1, 3, 5, ..., 99）
 * - 线程2 输出所有偶数（2, 4, 6, ..., 100）
 * - 通过 Lock + Condition 机制确保输出顺序严格按照数字大小递增
 * - 输出结果：1, 2, 3, 4, 5, ..., 98, 99, 100
 * 
 * 同步机制说明：
 * - 使用 ReentrantLock 作为互斥锁，保证同一时刻只有一个线程执行
 * - 使用 Condition 实现线程间的等待/唤醒机制
 * - 通过 currentNumber 共享变量追踪当前应该输出的数字
 * - 每个线程输出数字后，检查下一个数字是否应该由自己输出
 *   - 如果是，继续输出；如果不是，等待另一个线程唤醒
 * 
 * @author Interview
 * @version 1.0
 */
public class AlternateNumberPrinter1 {



    static class Printer {
        private int current = 1;
        private final Lock lock = new ReentrantLock();
        private final Condition condition = lock.newCondition();

        private static final int number = 100;

        public void printOdd() {
            lock.lock();
            try {
                while (current<= number){
                    if (current % 2 == 1){
                        System.out.print(current + " ");
                        current++;
                        condition.signalAll();
                    }else {
                        condition.await();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            finally {
                lock.unlock();
            }
        }

        public void printEven() {
            lock.lock();
            try {
                while (current<= number){
                    if (current % 2 == 0){
                        System.out.print(current + " ");
                        current++;
                        condition.signalAll();
                    }else {
                        condition.await();
                    }
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        Printer printer = new Printer();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.submit(() -> {
            printer.printOdd();
        });
        executorService.submit(() -> {
            printer.printEven();
        });
        executorService.shutdown();

        try {
            if (!executorService.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)) {
                System.err.println("\n线程池未在规定时间内关闭");
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            System.err.println("主线程被中断");
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }


}

